import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Button } from "@/components/ui/button";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Spinner } from "@/components/ui/spinner";
import { useTranslation } from "react-i18next";
import { Trash2, AlertTriangle } from "lucide-react";
import { useUserDelete } from "@/hooks/use-user";
import { useUserStore } from "@/stores";
import { DeleteAccountSchema, type DeleteAccountFormData } from "@/schemas/delete-account";
import PasswordInput from "@/components/custom-ui/password-input";

export function DeleteAccount() {
  const { t } = useTranslation();
  const { user } = useUserStore();
  const { deleteUser, isDeleting } = useUserDelete();

  const [isOpen, setIsOpen] = useState(false);

  const form = useForm<DeleteAccountFormData>({
    resolver: zodResolver(DeleteAccountSchema()),
    defaultValues: {
      password: "",
    },
  });

  const handleOpenChange = (newOpen: boolean) => {
    setIsOpen(newOpen);

    // 重置表单
    if (!newOpen) {
      form.reset();
    }
  };

  const handleDeleteAccount = (data: DeleteAccountFormData) => {
    if (user?.has_password) {
      // 有密码的情况，需要传入密码
      deleteUser({ password: data.password });
    } else {
      // 没有密码的情况，直接删除
      deleteUser({});
    }
  };

  const isPasswordRequired = user?.has_password;
  const isFormValid = form.formState.isValid;
  const isDeleteDisabled = (isPasswordRequired && !isFormValid) || isDeleting;

  return (
    <div className="pb-6 border-b">
      <div className="flex justify-center">
        <AlertDialog open={isOpen} onOpenChange={handleOpenChange}>
          <AlertDialogTrigger asChild>
            <Button variant="destructive" className="hover:cursor-pointer">
              <Trash2 className="w-4 h-4 mr-2" />
              {t("Delete Account", { defaultValue: "Delete Account" })}
            </Button>
          </AlertDialogTrigger>
          <AlertDialogContent>
            <AlertDialogHeader>
              <div className="flex items-center gap-2">
                <AlertTriangle className="w-5 h-5 text-destructive" />
                <AlertDialogTitle>
                  {t("Delete Account", { defaultValue: "Delete Account" })}
                </AlertDialogTitle>
              </div>
              <AlertDialogDescription className="space-y-4">
                {isPasswordRequired ? (
                  <>
                    <p>
                      {t(
                        "This action cannot be undone. This will permanently delete your account and remove your data from our servers.",
                        {
                          defaultValue:
                            "This action cannot be undone. This will permanently delete your account and remove your data from our servers.",
                        }
                      )}
                    </p>
                    <form onSubmit={form.handleSubmit(handleDeleteAccount)} className="space-y-2">
                      <div>
                        <PasswordInput
                          id="password"
                          {...form.register("password")}
                          placeholder={t("Enter your password to confirm", {
                            defaultValue: "Enter your password to confirm",
                          })}
                          autoComplete="current-password"
                        />
                        {form.formState.errors.password && (
                          <p className="text-sm text-destructive mt-1">
                            {form.formState.errors.password.message}
                          </p>
                        )}
                      </div>
                    </form>
                  </>
                ) : (
                  <p>
                    {t(
                      "Are you sure you want to delete your account? This action cannot be undone and will permanently delete your account and remove your data from our servers.",
                      {
                        defaultValue:
                          "Are you sure you want to delete your account? This action cannot be undone and will permanently delete your account and remove your data from our servers.",
                      }
                    )}
                  </p>
                )}
              </AlertDialogDescription>
            </AlertDialogHeader>
            <AlertDialogFooter>
              <AlertDialogCancel disabled={isDeleting}>
                {t("Cancel", { defaultValue: "Cancel" })}
              </AlertDialogCancel>
              <AlertDialogAction
                onClick={form.handleSubmit(handleDeleteAccount)}
                disabled={isDeleteDisabled}
                className="bg-destructive text-primary-foreground hover:bg-destructive/80 cursor-pointer"
              >
                {isDeleting ? (
                  <>
                    <Spinner className="mr-1" />
                    {t("Deleting...", { defaultValue: "Deleting..." })}
                  </>
                ) : (
                  t("Delete Account", { defaultValue: "Delete Account" })
                )}
              </AlertDialogAction>
            </AlertDialogFooter>
          </AlertDialogContent>
        </AlertDialog>
      </div>
    </div>
  );
}
